package top.szhome.develop.generator;

import top.szhome.develop.entity.Datasource;
import top.szhome.develop.entity.Model;
import top.szhome.develop.entity.Project;
import top.szhome.develop.entity.Property;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.*;

/**
 * 代码生成上下文
 *
 * @author 唐加利
 * @date 2023/9/2
 **/
public class Context extends HashMap<String, Object> {

    /**
     * 设置代码生成
     * @param project
     * @return
     */
    public Context setProject(Project project) {
        return set("project", project);
    }

    /**
     * 设置数据源
     * @param datasource
     * @return
     */
    public Context setDatasource(Datasource datasource) {
        return set("datasource", datasource);
    }

    /**
     * 设置代码生成批次涉及的所有模型
     * @param models
     * @return
     */
    public Context setModels(Map<Model, List<Property>> models) {
        return set("models", models);
    }

    /**
     * 设置代码生成批次当前模型
     * @param model
     * @return
     */
    public Context setModel(Model model){
        return set("model", model);
    }

    private static Map<String, String> TYPE_MAPPING = new HashMap<>();
    static {
        TYPE_MAPPING.put(Date.class.getSimpleName(), Date.class.getCanonicalName());
        TYPE_MAPPING.put(LocalDate.class.getSimpleName(), LocalDate.class.getCanonicalName());
        TYPE_MAPPING.put(LocalTime.class.getSimpleName(), LocalTime.class.getCanonicalName());
        TYPE_MAPPING.put(LocalDateTime.class.getSimpleName(), LocalDateTime.class.getCanonicalName());
    }

    /**
     * 设置代码生成当前表的
     * @param properties
     * @return
     */
    public Context setProperties(List<Property> properties) {
        // 处理要导入的类
        Set<String> imports = new HashSet<>();
        for(Property property : properties){
            String fieldType = property.getFieldType();
            String type = TYPE_MAPPING.get(fieldType);
            if(type == null || type.startsWith("java.lang.")){
                continue;
            }
            imports.add(type);
        }
        set("imports", imports);

        return set("properties", properties);
    }

    /**
     * 设置上下文属性
     * @param key
     * @param value
     * @return
     */
    public Context set(String key, Object value) {
        put(key, value);
        return this;
    }

    /**
     * 获取包路径
     * @return
     */
    public String getPackage() {
        Project project = getProject();
        Model model = getModel();
        String basePkg = project.getBasePkg();
        String module = model.getModule();
        return basePkg + "." + module;
    }

    /**
     * 获取工程
     * @return
     */
    public Project getProject(){
        return (Project) get("project");
    }

    /**
     * 获取模型
     * @return
     */
    public Model getModel(){
        return (Model) get("model");
    }

}
